package com.ky.home.controller;


import cn.hutool.core.convert.NumberWithFormat;
import com.ky.common.config.SystemConfig;
import com.ky.common.param.NewsReviewAdd;
import com.ky.common.util.JwtUtil;
import com.ky.common.vo.R;
import com.ky.home.entity.News;
import com.ky.home.entity.NewsReview;
import com.ky.home.mapper.NewsMapper;
import com.ky.home.mapper.NewsReviewMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author pl
 * @since 2024-06-21
 */
@RestController
@RequestMapping("/home")
public class NewsReviewController {
    @Autowired
    private NewsReviewMapper newsReviewMapper;
    @Autowired
    private NewsMapper newsMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    @RequestMapping("/selectNewsReview/{newId}")
    public R selectNewsReview(@PathVariable("newId") int newId) {
      return R.fail("查询成功");
    }

    @RequestMapping("/addNewsReview")
    public R addNewsReview(HttpServletRequest request, @RequestBody NewsReviewAdd newsReviewAdd) {
        String token = request.getHeader(SystemConfig.HEADER_TOKEN);
        Integer id = ((NumberWithFormat) JwtUtil.parseToken(token, "id")).intValue();
        int newsId = (int) redisTemplate.opsForValue().get("newsId");
        NewsReview newsReview = new NewsReview()
                .setNewsId(newsId)
                .setContent(newsReviewAdd.getContent())
                .setUserId(id)
                .setTime(new Date());
        News news = newsMapper.selectById(newsId);
        if (news!=null){
            news.setReviews(news.getReviews()+1);
            newsMapper.updateById(news);
        }
        int insert = newsReviewMapper.insert(newsReview);
        if (insert>0){
            return R.ok("添加评论成功");
        }
        return R.fail("添加评论失败");

    }

}

